package com.jc.service.api.appgame;

import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import com.alibaba.fastjson.JSONObject;
import com.jc.common.util.Base64Util;
import com.jc.ds.base.service.BaseServiceException;
import com.jc.ds.model.GameUser;
import com.jc.ds.model.UserVrtAddress;
import com.jc.framework.enums.Booleans;
import com.jc.framework.enums.Conclusion;
import com.jc.framework.enums.LogType;
import com.jc.framework.util.SpringUtils;
import com.jc.framework.web.ResponseBaseModel;
import com.jc.framework.web.ResponseResultModel;
import com.jc.service.api.BaseDual;
import com.jc.service.api.appgame.model.AppGameUser;
import com.jc.service.api.appgame.model.Param;
import com.jc.service.apilog.ApiLogService;
import com.jc.service.gameuser.GameUserService;
import com.jc.service.uservrtaddress.UserVrtAddressService;
import com.jc.service.vrt.VrtService;
import com.jc.service.vrt.model.Address;
import com.jc.service.vrt.model.VrtResult;

/***
 * 处理APP游戏登录的接口
 * 
 * @author Administrator
 *
 */
public class login extends BaseDual<Param> {

	private GameUserService gameUserService = SpringUtils.getBean(GameUserService.class);
	private UserVrtAddressService userVrtAddressService = SpringUtils.getBean(UserVrtAddressService.class);
	private VrtService vrtService = SpringUtils.getBean(VrtService.class);
	private ApiLogService apiLogService = SpringUtils.getBean(ApiLogService.class);

	public ResponseEntity<?> dual(JSONObject data) {
		Param param = getData(data);
		String jsonData = null;
		try {
			if(StringUtils.isBlank(param.getEncrypt())) {
				throw new BaseServiceException("参数错误,请重试!");
			}
			
			jsonData = Base64Util.decode(param.getEncrypt());
			getLoger().info("APP 游戏调用登录接口 -----> 参数 : {} " , JSONObject.toJSONString(param));
			
			// 请求VRT社区
			Map<String, Object> paramMap = new HashedMap<String, Object>();
			JSONObject loginObject = JSONObject.parseObject(jsonData);
			paramMap.put("username", loginObject.getString("userName"));
			paramMap.put("password", loginObject.getString("passWord"));
			
			VrtResult result = null;
			try {
				result = vrtService.pushVrtClub(paramMap, "/login", LogType.NOTICE_VRT_CLUB_LOGIN);
			} catch (Exception e) {
				getLoger().error("请求VRT社区登陆, 出现错误 : {} , {}" , e.getMessage() , e );
				throw new BaseServiceException("请求VRT社区异常,请重试!");
			}
			if (result == null) {
				getLoger().error("登录错误, 请求VRT社区返回值为空 !");
				throw new BaseServiceException("登录异常,请重试!");
			}
			// 判断VRT社区返回的结果, 如果登录成功，则将用户信息更新至本地用户表，如果登录失败则直接把错误原因反馈到游戏系统
			if (result.getReturnCode() == 0) {
				// 登录成功，更新本地数据库用户信息, 然后返回登录成功结果
				Long userId = result.getUserId();
				String nickName = result.getNickname();
				String userPic = result.getUserPic();
				List<Address> vrtAddressArray = result.getAddress();

				GameUser gameUser = gameUserService.queryGameUser(userId);
				if (gameUser == null) {
					GameUser _gameUser = new GameUser();
					_gameUser.setIsAgree(Booleans.FALSE.getName());
					_gameUser.setUserId(userId);
					_gameUser.setUserNickName(nickName);
					_gameUser.setUserPic(userPic);
					gameUserService.add(_gameUser, false);
				} else {
					gameUser.setUserPic(userPic);
					gameUser.setUserNickName(nickName);
					gameUserService.modify(gameUser, false);
				}
				// 先删除该用户所有VRT地址,再加入新取到的用户VRT钱包地址列表
				userVrtAddressService.removeVrtAdressByUserId(userId);
				if(CollectionUtils.isEmpty(vrtAddressArray)) {
					getLoger().error("无钱包地址---------------------------------> "  );
				}else {
					getLoger().error("有钱包地址---------------------------------> " + vrtAddressArray.size());					
				}
				for (Address adr : vrtAddressArray) {
					
					// 组织用户VRT钱包地址，如果该用户只有一个VRT地址，则直接设置为默认交易地址，如果有多个这里不做设置。需要用户自己在转账交易的时候进行设置。
					UserVrtAddress addr = new UserVrtAddress();
					addr.setAddressRemark(adr.getRemark());
					addr.setUserId(userId);
					addr.setUserVrtAddress(adr.getAddr());
					if (vrtAddressArray.size() == 1) {
						addr.setSelected(Booleans.TRUE.getName());
					} else {
						addr.setSelected(Booleans.FALSE.getName());
					}
					userVrtAddressService.add(addr, false);
				}
				
				apiLogService.addApiLog(LogType.APP_GAME_REQUEST_LOGIN, jsonData, Conclusion.OK, "", JSONObject.toJSONString(result));
				AppGameUser u = new AppGameUser();
				u.setNickName(gameUser.getUserNickName());
				u.setUserPic(gameUser.getUserPic());
				u.setUserId(""+gameUser.getUserId());
				return new ResponseEntity<>(new ResponseResultModel<AppGameUser>(u), HttpStatus.OK);
			} else {
				// 登录失败，直接返回错误结果
				apiLogService.addApiLog(LogType.APP_GAME_REQUEST_LOGIN, jsonData, Conclusion.FAIL, "", JSONObject.toJSONString(result));
				return new ResponseEntity<>(new ResponseBaseModel(29002,"登录失败,请检查用户名密码"), HttpStatus.OK);
			}			
		} catch (Exception e) {
			String error = e.getMessage();
			if(e.getMessage().length() > 150) {
				error = StringUtils.substring(e.getMessage(), 0, 150);
			}
			
			getLoger().error("登录错误 : 原因 : {} , {}", e.getMessage(), e);
			
			apiLogService.addApiLog(LogType.APP_GAME_REQUEST_LOGIN, jsonData , Conclusion.FAIL, "系统异常", error);
			
			return new ResponseEntity<>(new ResponseResultModel<>("登录异常, 发生系统错误"), HttpStatus.OK);
		}

	}
}
